'use strict';

const Controller = require('egg').Controller;
const { getCookieValue } = require('../public/processCookies');
const { axios } = require('../public/httpHelper');
const qs = require('qs');
const configDefault = require('../../config/config.default')();
const md5 = require('md5');
/**
* @controller UserAdminController 注释必写，swagger-doc是根据这段注释来生成接口的 ）。
*/
class UserAdminController extends Controller {
  /**
    * @summary 用户登录。
    * @description 用户登录。
    * @router post /login
    * @request body useradmin value 传入参数
    */
  async login() {
    console.log('login');
    try {

      const params = this.ctx.request.body;
      // // 查询数据库里的信息
      const result = await this.ctx.service.userAdmin.login(params);
      const userrole = await this.ctx.service.userAdmin.findById(result.id);
      const list = await this.ctx.service.role.roleuser(userrole);
      if (result == null) {
        this.ctx.body = {
          msg: 'username is wrong',
          status: 1,
        };
      } else if (result.password == md5(params.password)) {
        this.ctx.session.admin = {
          id: result.id,
          username: result.username,
          nickname: result.nickname,
          language: result.language,
          is_super: result.is_super,
          tid: result.tenantadminId,
        };
        this.ctx.body = {
          msg: 'login successful',
          status: 3,
          data: list,
        };
        global.log.desc = `${this.ctx.session.admin.nickname} login`;
      } else {
        this.ctx.body = {
          msg: 'password is wrong',
          status: 2,
        };
      }
    } catch (error) {
      console.log('log catch error');
      console.log(error);
    }
  }
  /**
    * @summary 用户登录。
    * @description 用户登录。
    * @router post /loginAuth
    * @request body loginauth value 传入参数
    */
  async loginAuth() {
    console.time('loginAuth');
    const { userid } = this.ctx.request.body;
    const userrole = await this.ctx.service.userAdmin.findById(userid);
    const list = await this.ctx.service.role.roleuser(userrole);
    console.timeEnd('loginAuth');
    if (list) {
      this.ctx.body = {
        msg: '',
        status: 3,
        data: list,
      };
    } else {
      this.ctx.body = {
        msg: 'can not get permission information',
        status: 2,
      };
    }
  }
  /**
    * @summary 用户登录。
    * @description 用户登录。
    * @router post /getACS
    * @request body useradmin value 传入参数
    */
  async getACS() {
    try {
      const cookieInfo = this.ctx.cookies.get('token', {
        signed: true, // 对cookie进行签名 防止用户修改cookie
        encrypt: true, // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密,这里要注意配置文件里的cookie.key和授权中心的key保持一致
      });
      console.log(cookieInfo);
      const params = this.ctx.request.body;
      const result = await this.ctx.service.tenantAdmin.getACS(params);
      this.ctx.body = {
        msg: '',
        status: 200,
        data: result.acsURL,
      };
    } catch (error) {
      console.log(error);
      this.ctx.body = {
        msg: '',
        status: 500,
        data: error,
      };
    }
  }
  /**
    * @summary 查询账户列表。
    * @description 查询账户列表。
    * @router get /useradminlist
    * @request query integer limit
    * @request query integer page
    */
  async useradminlist() {
    const params = this.ctx.query;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;
    const result = await this.ctx.service.userAdmin.list(params);
    this.ctx.body = {
      msg: '',
      status: 200,
      count: result.data.count,
      data: result.data.rows,
    };
  }
  async userCreate() {
    /**
    * @summary 用户创建。
    * @description 用户创建。
    * @router post /useradmincreate
    * @request body useradmincreate value 传入参数
    */
    const params = this.ctx.request.body;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    params.tid = tid;

    const data = qs.stringify({
      password: params.password,
      age: params.age,
      firstname: params.firstname,
      lastname: params.lastname,
      email: params.email,
      tid,
      language: params.language,
    });
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/addTenantUser`,
      data,
    };
    let response;
    try {
      response = await axios(config);
    } catch (error) {
      console.log(error);
    }
    global.log.desc = 'create useradmin';
    global.log.after = `{email:${params.email},firstname:${params.firstname},lastname:${params.lastname},language:${params.language}}`;
    if (response.status === 200 && response.statusText === 'OK') {
      this.ctx.body = {
        msg: 'success',
      };
    } else {
      this.ctx.body = {
        msg: 'fail',
      };
    }
  }

  async userUpdate() {
    /**
    * @summary 用户更新。
    * @description 用户更新。
    * @router post /useradminupdate
    * @request body useradmincreate value 传入参数
    */
    const params = this.ctx.request.body;
    // TODO 这里需要改
    const result = await this.ctx.service.userAdmin.update(params);
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async userDelete() {
    /**
    * @summary userDelete
    * @description userDelete
    * @router get /useradmindelete
    * @request query string id
    */
    const params = this.ctx.query;
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/deleteUsers`,
      data: qs.stringify({ id: params.id }),
    };
    let response;
    try {
      response = await axios(config);

    } catch (error) {
      console.log(error);
    }

    // const userResult = await this.ctx.model.UserAdmin.findOne({ where: { id: params.id } });
    // const result = await this.ctx.service.userAdmin.delete(params);
    global.log.desc = `delete useradmin ${response.data.msg}`;
    this.ctx.body = {
      msg: response.data.msg,
    };
  }
  async userEditPassword(){
     /**
    * @summary userEditPassword
    * @description userEditPassword
    * @router get /usereditpassword
    * @request query string id
    */
      const params = this.ctx.query;
      const config = {
        method: 'get',
        url: `${configDefault.authorization.url}/editPassword?userId=${params.id}`,
      }
      let response;
      try {
        response = await axios(config);
      } catch (error) {
        console.log(error);
      }
      global.log.desc = `${params.email} ${response.data.msg}`;
      this.ctx.body = {
        flag:response.data.result.flag,
        msg: response.data.result.msg,
      };
  }
  async bindrole() {
    /**
    * @summary bindrole
    * @description bindrole
    * @router post /bindrole
    * @request body bindrole value 传入参数
    */
    const params = this.ctx.request.body;
    const { id: tid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    const { name } = getCookieValue(this.ctx.cookies, 'token', 'user');
    params.tid = tid;
    const role = [];
    for (let i = 0; i < params.rolelist.length; i++) {
      const roleResult = await this.ctx.modelmysql.RoleInfo.findOne({ where: { id: params.rolelist[i] } });
      role.push(roleResult.name);
    }
    const result = await this.ctx.service.userAdmin.bindrole(params);
    if (params.rolelist.length != 0) {
      global.log.desc = `useradmin ${name} bindrole ${role}`;
    } else {
      global.log.desc = 'useradmin unbind';
    }
    this.ctx.body = {
      msg: result.msg,
    };
  }
  async getrolelist() {
    /**
    * @summary getrolelist
    * @description getrolelist
    * @router get /getrolelist
    * @request query string id
    */
    const params = this.ctx.query;
    const result = await this.ctx.service.userAdmin.getrolelist(params);
    this.ctx.body = {
      data: result,
      status: 200,
    };
  }
}

module.exports = UserAdminController;
